package fun.linze.order.service.impl;

import fun.linze.order.bean.Order;
import fun.linze.order.service.OrderService;
import fun.linze.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    LoadBalancerClient loadBalancerClient;



    @Override
    public Order createOrder(Long productId, Long userId) {
        Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);
        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setUserId(userId);
        order.setNickName("林泽");
        order.setAddress("商城");
        order.setProductList(null);
        return order;
    }
    private Product getProductFromRemote(long productId) {

        //获取商品服务的所有实例
        List<ServiceInstance> instances= discoveryClient.getInstances("service-product");
        ServiceInstance instance =instances.get(0);
        String url= "http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;


        log.info("请求远程服务的URL: {}", url);
        //给远程发送请求
        Product product= restTemplate.getForObject(url,Product.class);
        return product;
    }

    ///负载均衡
    private Product getProductFromRemoteWithLoadBalancer(long productId) {
        ServiceInstance instance = loadBalancerClient.choose("service-product");
        String url= "http://"+instance.getHost()+":"+instance.getPort()+"/product/"+productId;
        log.info("负载均衡请求远程服务的URL: {}", url);
        Product product= restTemplate.getForObject(url,Product.class);
        return product;
    }

    ///基于注解的负载均衡
    private Product getProductFromRemoteWithLoadBalancerAnnotation(long productId) {

        ///service-product会被动态替换
        String url= "http://service-product/product/"+productId;


        ///这个log没有任何意义，因为service-product在发送时才会被动态替换
        ///如果想检测url可以添加拦截器
        ///log.info("负载均衡请求远程服务的URL: {}", url);


        Product product= restTemplate.getForObject(url,Product.class);
        return product;
    }

}
